﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using EPiServer.DataAbstraction;

namespace OpenWaves.EPiServer.TagsProperty
{
    public static class CategoryExtensions
    {
        public static IList<Category> GetDescendants(this Category category)
        {
            var categories = new List<Category>();

            categories.AddRange(category.Categories.Cast<Category>());

            foreach (Category c in category.Categories)
            {
                categories.AddRange(c.GetDescendants());
            }

            return categories;
        }
    }

    public class CategoryTagsProvider : ITagsProvider
    {
        private readonly IList<Category> _categories;

        public CategoryTagsProvider()
        {
            _categories = Category.GetRoot().GetDescendants();
        }

        public IEnumerable<Tag> GetTags()
        {
            
            return _categories
                .Select(c => new Tag
                {
                    Id = Convert.ToString(c.ID),
                    ParentID = Convert.ToString(c.Parent.ID),
                    Name = c.Name
                });
        }

        public IEnumerable<Tag> GetTagsByIDs(IEnumerable<string> ids)
        {
            return ids.Select(this.GetTagByID);
        }

        public Tag GetTagByID(string id)
        {
            return _categories
                .Where(c => c.ID == Convert.ToInt32(id))
                .Select(c => new Tag
                    {
                        Id = Convert.ToString(c.ID),
                        ParentID = Convert.ToString(c.Parent.ID),
                        Name = c.Name
                    })
                .FirstOrDefault();
        }
    }
}